﻿#include "MeUtil.h"

#ifdef _WIN32
#include <QDateTime>
#else
#include <sys/time.h>

#include <QCoreApplication>
#include <QEventLoop>
#include <QTime>
#endif

QString MeUtil::createFolder(const QString &path){

    QDir dir(path);
    if ( dir.exists(path)){
        return path;
    }
    // 如果是根目录或者是E:, 无法找到, 不存在, 那么返回空
    if (path.lastIndexOf('/') <= 0) {
        return "";
    }
    QString parentDir = createFolder(path.mid(0, path.lastIndexOf('/')));
    QString dirname = path.mid(path.lastIndexOf('/') + 1);
    QDir parentPath(parentDir);
    if ( !dirname.isEmpty() ) {
        if(!parentPath.mkpath(dirname)) {
            return "";
        }
    }
    return parentDir + "/" + dirname;
}

void MeUtil::createFolder(std::string folderPath)
{
    // 建立输出文件夹
    QString qStrFolder = QString::fromStdString(folderPath);
    QFileInfo fileInfo(qStrFolder);
    if (!fileInfo.exists() ) {
        QDir dir;
        dir.mkdir(qStrFolder);
    }
}

#ifdef WIN32
ulong MeUtil::getCurrentTime() {
    QDateTime curTimeStamp = QDateTime::currentDateTime();
    return curTimeStamp.toMSecsSinceEpoch();
}
#else
ulong MeUtil::getCurrentTime() {
    struct timeval time;
    gettimeofday(&time, nullptr);
    return ulong(time.tv_sec * 1000 + time.tv_usec / 1000);
}

void MeUtil::msleep(long msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while (QTime::currentTime() < dieTime) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, msec);
    }
}

#endif
